package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import sun.misc.BASE64Decoder
import sun.misc.BASE64Encoder

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 *
 * @Title: cn.com.callback-apiBatchSignContract
 * @Description:ngsapitask-ph 合同批量发送
 * @Author: 胡策富
 * @Date 2023/8/4 14:30
 *
 */
public class apiBatchSignFlag_Dev implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiBatchSignFlag_Dev.class);

    // 设置的信号变量，最好使用volatile 关键字或者使用AtomicInteger原子类
    private volatile static int flag = 0;

    @Override
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        long startTime = System.currentTimeMillis();

        // 初始化返回参数
        JSONObject result = new JSONObject();

        String method = request.getMethod();
        log.debug("获取请求方式：" + method);

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("Call Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> mapParam = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("Call Parameter-" + key + ":" + value);
            mapParam.put(key, value);

        }

        // 获取调用数据
        String callPram = "";
        if (method.equals("GET")) {
            callPram = request.getQueryString();
            log.info("接收调用GET参数信息：" + callPram);
        } else if (method.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                callPram += line;
            }
            log.info("接收调用POST报文信息：" + System.getProperty("line.separator") + callPram);
        }

        String callbackType = "";
        String batchId = "";

        try {
		
        JSONObject callJson = JSONObject.fromObject(callPram);
        String username_ucode = callJson.getString("username_ucode");
        System.out.println("username_ucode:"+username_ucode);
		
            //获取回调类型
            callbackType = request.getParameter("callbackType");
            batchId = request.getParameter("batchId");
            switch (callbackType) {
                case "暂停":
                    flag = Integer.valueOf(request.getParameter("flag"));
                    break;
                case "批量发送":
                    pushContract(eliteBean, batchId);
                    break;
            }
            result.put("code", "200");
            result.put("msg", "批次操作完成");

        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "获取请求参数异常(" + e.getMessage() + ")");
            log.error("获取请求参数异常：" + e.getMessage());

        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "合同批量-控制Main", "apiBatchSignContract", callPram, result.toString(), (System.currentTimeMillis() - startTime).toString(), method + ":" + mapParam.toString());
        }
        return result.toString();
    }

    public static boolean pushContract(EliteBean eliteBean, String batchId) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Boolean result = false;
        int count = 0;
        while (!result && count < 120) {
            try {
                Thread.sleep(5 * 1000); //设置暂停的时间 5 秒
                count++;
                log.debug(batchId + " -- " + sdf.format(new Date()) + " 第" + count + "次" + " Flag:" + flag);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}